import React, { useState, useEffect} from 'react';
import { useHistory } from "react-router-dom";
import Btn from "../../../components/btn/Btn";
import UserMsg from "../../outUser/userMsg/UserMsg"; 
import http from '../../../model/http';
import code from "../../../model/code";
import './cardCharging.less'; 
import {InputItem, Toast, Modal,Picker, List, TextareaItem} from 'antd-mobile';
import Header from '../../../components/header/Header';
const Item = List.Item;
function CardCharging() { 
  const history = useHistory();
  const [money,setMoney] = useState('')
  const [userData,setUserData] = useState([])

  const [typeSelectData, setTypeSelectData] = useState([])

  const [typeSelectVal, setTypeSelectVal] = useState([-1])
  const [mark, setMark] = useState('')
  const [consultCondition,setConsultCondition] = useState('')

    // 开单人/销售员 下拉菜单
    const [salesperson, setSalesperson] = useState([])
    // 下拉的值
    const [currentSalesperson, setCurrentSalesperson] = useState([-1])


  /*渲染完成*/
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect( async ()=>{
      
    userDataFunc(history.location.state.customerCrmId)
    getSaleperson()
  },[])

  const userDataFunc = async (userid) => {
    const result = await http.post('/order/kdInfoInit', {
      customerCrmId: userid
    })
    if (result.code == 0) {
      setUserData(result.data[0]) 

      let resultTypeData = result.client_demand.map(item => {
        return {
          label: item.name,
          value: item.dept_id,
          children: 
            item.subdata.map(item2 => {
              return {
                label: item2.name,
                value: item2.tb_client_demand_id
              }
            })  
          
        }
      })
      console.log(resultTypeData)
      setTypeSelectData(resultTypeData)
    }
  }

  const getSaleperson =async ()=>{
    // http://wxwork.gzsg.cn/wxwork/order/getKDManagerList?hosId=1&userId=LiHao&managerId=1000127

    const result = await http.post('/order/getKDManagerList')
    if (result.code == 0) {
        let list =[]
        result.data.forEach(item => {
            let obj={}
            obj.label = item.user_name + "("+item.account+")"
            obj.value = item.managerId
            // obj.account= item.account
            list.push(obj)
        })
        console.log("开单人列表",list)
        setSalesperson(list)
        setCurrentSalesperson([list[0].value ])
    }

}


  const getCurrentSalesperson =(v)=>{
    console.log(v)
    setCurrentSalesperson(v)
  }


  // 点击下拉
  const getTypeSelectVal = (v) => {
    console.log(v)
    setTypeSelectVal(v)
  }
  // 充卡
  const onSubmit = () => {
    if (money == '') { Toast.fail('请输入需要充值的金额'); return };
    if (mark == ''){Toast.fail('请输入备注信息'); return};
    if (typeSelectVal[0] < 0){Toast.fail('请选择顾客主诉项目'); return};
 
    
    Modal.alert('提示',   `是否确定充值${money}元`, [
      { text: '取消' },
      {
        text: '确定', onPress: async () => {
          const result = await http.post('/order/subcard',{
            payable_amt:money,
            customerCrmId: history.location.state.customerCrmId,
            item_type_id: typeSelectVal[1],
            memo: mark,
            consult_condition:consultCondition,
            managerId:currentSalesperson[0]

          }) 
          if(result.code == 0){
            Toast.success(result.msg)
            setTimeout(() => {
              history.push('/billingPage/success',{
                comeType:'cardCharging',
                msg: result.msg,
                data:[],
                userInfo: [],
                projectData: [], 
                kdtime:result.kdtime,
                money: result.money,
                orderQRCode:result.orderQRCode,
                shareUrl:result.shareurl
              })
            }, 500);
            
          }else{
            Toast.fail(result.msg)
          }
        }
      }
    ])
    
  }
  
  

   
  return ( 
    <div className='v-card-charging'>
      <div className="body-background-div"></div>
      {/* <div style={{margin:'10px'}}>
        <UserMsg msg={history.location.state} />
      </div> */}
      
      <div className="content-box">
        
      <div className="hearder">
          <span>开单人/销售员</span> 
        </div>

        <div className="box-picker">
          <List>
            <Picker cols={1} extra={<span style={{color:'#bbb'}}>请选择开单人/销售员</span>}  data={salesperson} 
              value={currentSalesperson}
              onOk={v => getCurrentSalesperson(v)}
            >
              <Item arrow="horizontal"></Item>
            </Picker>
          </List>
        </div>


        
        <div className="hearder">
          <span>顾客主诉</span> 
        </div>
        <div className="box-picker">
          <List>
            <Picker cols={2} extra={<span style={{color:'#bbb'}}>请选择主诉项目</span>}  data={typeSelectData} 
              value={typeSelectVal}
              onOk={v => getTypeSelectVal(v)}
            >
              <Item arrow="horizontal"></Item>
            </Picker>
          </List>
        </div>
        <div className="hearder">
          <span>充值金额</span>
          <p>顾客目前账户余额:{userData.yc_amt}.00元</p>
        </div>
        <div className="center"> 
          <InputItem type='number' value={money} onChange={(v) => {
            
            if(v.substring(0,1) == 0){
              v = v.substr(0,1)
              setMoney('')
              
            }else{
              setMoney(v)
            }
            
          
          }} min="1" className="input-box" maxLength="6" placeholder="请输入要充值的金额，1~100万之间" /> 
        </div>
        
        <List className='g-p5-10 g-bg-f g-bdrs12 input-css'>
          <TextareaItem value={consultCondition} rows={5} count={100} onChange={setConsultCondition} placeholder='咨询情况，非必填' />
        </List>

        <List className='g-p5-10 g-bg-f g-bdrs12 input-css' style={{marginTop: '5px'}}>
          <TextareaItem value={mark} rows={5} count={100} onChange={setMark} placeholder='请输入备注信息...' />
        </List>
      </div>
      <div className='g-abs g-b0 g-l0 g-w100'  > 
        <Btn className="v-billing-box-btn" type='warning' 
          // onClick={()=>{billingGo('/billing/project?outUserId=')}}
          onClick={() => onSubmit()}
        >预存款开单</Btn>
         
      </div> 
      <Header />
    </div>
  )
}

export default CardCharging;
 